package initialize

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"time"
	common "user_service/config"
)

var db *mongo.Database

var client *mongo.Client

type MongoClient struct {
}

// 初始化连接MongoDB
func InitConnect() *mongo.Client {
	connStr := fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=admin",
		common.Configs.DB.User,
		common.Configs.DB.Password,
		common.Configs.DB.Host,
		common.Configs.DB.Port,
		common.Configs.DB.Name)

	// 连接到 MongoDB
	clientOptions := options.Client().ApplyURI(connStr)
	// 创建上下文并设置连接超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 连接到 MongoDB
	var err error
	client, err = mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Fatalf("Failed to connect to MongoDB: %v", err)
	}

	// 检查连接
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatalf("Failed to ping MongoDB: %v", err)
	}
	// 设置 MongoDB 数据库和集合
	db = client.Database(common.Configs.DB.Name)

	fmt.Println("MongoDB Connect to" + db.Name())

	return client
}

// 连接MongoDB 返回一个集合
func (mc *MongoClient) connectColl(collection string) *mongo.Collection {
	coll := db.Collection(collection)
	return coll
}
